<?php
/*
  +----------------------------------------------------------------------+
  | PHP Version 5                                                        |
  +----------------------------------------------------------------------+
  | Copyright (c) 1997-2004 The PHP Group                                |
  +----------------------------------------------------------------------+
  | This source file is subject to version 3.0 of the PHP license,       |
  | that is bundled with this package in the file LICENSE, and is        |
  | available through the world-wide-web at the following url:           |
  | http://www.php.net/license/3_0.txt.                                  |
  | If you did not receive a copy of the PHP license and are unable to   |
  | obtain it through the world-wide-web, please send a note to          |
  | license@php.net so we can mail you a copy immediately.               |
  +----------------------------------------------------------------------+
  | Author:  Harun Yayli <harunyayli at gmail.com>                       |
  +----------------------------------------------------------------------+
*/
require_once("upyun.class.php");

/*
try {
    echo "=========获取目录文件列表\r\n";
    $list = $upyun->getList('/demo/');
    var_dump($list);
    echo "=========DONE\r\n\r\n";
}
catch(Exception $e) {
    echo $e->getCode();
    echo $e->getMessage();
}
*/

$VERSION='$Id: upyun.php 2014-05-16 20:17:56Z hradtke $';

define('OPERATOR_NAME','liuwt123'); 	// Admin Username
define('OPERATOR_PASSWORD','wszgrwazg');  	// Admin Password
define('BUCKET_NAME','liuwt123');  	// Admin Password
define('DATE_FORMAT','Y/m/d H:i:s');
define('GRAPH_SIZE',200);
define('MAX_ITEM_DUMP',50);

$extensions = array(
	"avi" => "R0lGODlhEAAQAMQAADExYzExnGMxnGNjY86cAM7O/6XO9//OMcbexqWlpc6cY87v/5xjY0pKSlJS Us7OY5ycY///92OcnM7OAP/OY5xjAP//nGNjnP/OAP+cAISEhMbGxgAAAP///////wAAACH5BAEA AB4ALAAAAAAQABAAAAVsoCdqXWmWnOhZbGtl55Z6GAFUWQ5vpkx3FwEAkdtoeJwkBwO8BAEM42aK YjovAcDAqCFVgdlLkWpaRgCXUrGHxLjfmAyVh1R179N5Z+Yh5XkddHt2gYF0UoMjPYF+KIQnkIke SpSVfCqYmR4hADs= ",
	"default" => "R0lGODlhEAAQAKIAAMbGxoSEhAAAAP///////wAAAAAAAAAAACH5BAEAAAQALAAAAAAQABAAAAMq SDTcHSou5wKUtI6rchaRR4Gd2JCTOaAqw7avGpuzWHv3F8KR4P/AHyEBADs= ",
	"doc" => "R0lGODlhEAAQAKIAAISEhMbGxgAA/wAAAP///////wAAAAAAACH5BAEAAAUALAAAAAAQABAAAANC WArU3kMVQSt9Ic7XRAsBkU1W9RFDOlxee4Zo6Yp0bDEeZ5tEzq0y30NTYOiGEuMRklw6iMol1MlU qK5YomTLLSQAADs= ",
	"folder" => "R0lGODlhEAAQAKIHAPf39///zpycAP/OnM7OYwAAAP//nP///yH5BAEAAAcALAAAAAAQABAAAANF eLrcKxAW90AIxojpBPkgEUWKcJ3oZRCTmb2wMbCHG8s4bd+DrGOwnnDVAgZxs+JrKEzWAkzkwOkJ WUGcgnbL5VK+YHACADs= ",
	"htm" => "R0lGODlhEAAQAPcAAOf3/+/3/0qt3imU5ymc5zFKc9bv/63O/2trnDFztVKMvXNzpXuErWOczmNj lDGc7/f3973e92OUtaXG52OEpa3W91JSjL3O/1pajEJjhFpalDGU7yF7vbXG1krW/3ucvZzv/7Xe /4yt1rXO/3Ot3pS9563O7zml9zGl94zW7yml5629zjmU3kp7rULG92O13lK9/4zv/ymt787n962t /0qUzq3W/3OEtTmt9zm17ym17zFSeyml75Slzpy13rXW73PW/+/v9zmExoyctVLW9ymM50Jaeym1 98bn9ymU3oSlxpyt1rXW90prlCGU59bn9ymc75S91jG99yGc51JrjEKt/zG192uMrVpzjDlzpWPO /yGMziFKc633/5Tn/ylajJTG/3P3/6Xn/4TG3nucrSmMxoTn/73O50qt7ylzpUK1/1qt58be9zG1 /zGt/97n79bn/9be7zm19ymU78bn7ymE3imt/zmMzpT3/zGM3sbW7973/3vG5zmc53OMnDm9/2Pn /6Xe7yFSeyGM3pTe71JShMbW3jm991rO/7XW/3vG/ymEzjlrlGu97ymM3jGt9+fv987e90LO/zGc 3jmc98bn/97v/87n//f//73e/3Nzc////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAJwALAAAAAAQABAA AAjTADkJ3ERwE4SDQW4IXDgQ0yZMECHegMFQIISIHRRIwITAAYKKAkIKGALAxJkAAS5oWugFTxgP R3KsYHIy5UpOIFK8ILBFBQE5HSwBAKCSkwCdBPYA4ECAUgtLUEesVKDEBQEFWB9UyWAg6spNLlRs KUC27CUDBg6sbGCFwKBLlxIkqEGCDVy1nKyUQTFnQ4IHiMRQqEQYbxJOHE6cUANkjJEfhCvhbSPw S4EdRsgwycQ5E15OLVqsGFEhUedMITzfFMhgwYKOGhxowKDBwuqKuBcGBAA7 ",
	"jpg" => "R0lGODlhEAAQALMAAEGyQVBcUe3x71KnzqmpsDc3OtLV1UJjnCEhIcbGxoSEhISEAAD/AP///wAA AP///yH5BAEAAA8ALAAAAAAQABAAAAR98EmXqk2quem6/5n2LEvTlOS5KN6YoiZ5KS9Zmw327R2O SQ+HQEAABBK4HKuDKAAADIYRqXQgroVs9gkoKIMhxSERuD6PigkyMCAUEIMy4zdpEAYDRMBw1Kcn XgUCBgYEBg0CCH9BiWUBBQRDDQqLDoh8TQGamosPlJ+gnxEAOw== ",
	"js" => "R0lGODlhEAAQAKIAAISEAMbGxoSEhP//AAAAAP///////wAAACH5BAEAAAYALAAAAAAQABAAAANJ aFLcLSbG5ZyAkla2sOJOQDTEVGhFIIhM+WkDEcytSQ1x5aKks28tkglYGBWHp4tgFKh9CoNeynnD DVRFKonA5QqfRGd3TOYaEgA7 ",
	"swf" => "R0lGODlhEAAQANUAAEpKSmt7jN7n5/f3787W3gAxUr29ve/392tra1paWq2trc7O1gAhQs7OzoSU nJSUnFpzhDExMXuMnLXGzqW1xmuElL3G1gBKa4ycpa21vVJrexBahO/v93uEjBhSc5SlrQApUpyt vUpje2Nze7W9zmt7lGuMpZScpVp7lFprhN7e59bW1oyMjO/373t7e+/n7wAAAP///////wAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAADIALAAAAAAQABAAAAaUQJkr RizGIjCZcjlstWKvWAuwSi5lo+gB+noBYtUrYkBsdb2wtGuJ0EKfXNZa+X2tNBiKBDN4yZcJUhAC HAQgEw5+CIADDwJEFyYqAX5zMhExgzETFwUqC5VLXwEEKiAoMZ8rLIt0MQoLDAWpBBChSpgtIwQr Ki8BBjF/rlAPEgEODUSsokZ2ZMuWAGnU1WpX2NlLQQA7 ",
	"txt" => "R0lGODlhEAAQAKIAAISEhMbGxgAAAP///////wAAAAAAAAAAACH5BAEAAAQALAAAAAAQABAAAAM5 SDQA7O0pAsQYFl8rhHJXKGIeRWYn+aWjarZit3ZoXILwdueh/PI+XC7I0806MCItuSv6CLSoVJEA ADs= ",
	"zip" => "R0lGODlhEAAQAMQAAN6UAABjlIzW///31v/GawCU3gAxUv/WjP/ntYSEhADe3v+9Sv+tIf+tAGuM /2vG////9///jACEhMbGxv8AAAAAAP///////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEA ABcALAAAAAAQABAAAAVO4HVZZElKYiqappSoK3taryqzVUpZQaE4styFQixWKjjRbkBoHJEmIWVw WACeySGCALges6veL2gjQcEjy/NsLt/aqXdJGJPTL+v8UxQCADs= "
);
$extensions['jpeg'] = $extensions["jpg"];
$extensions['docx'] = $extensions['xlsx'] = $extensions["xls"] = $extensions['pptx'] = $extensions["ppt"] = $extensions["doc"];

////////// END OF DEFAULT CONFIG AREA /////////////////////////////////////////////////////////////

///////////////// Password protect ////////////////////////////////////////////////////////////////
if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW']) ||
           $_SERVER['PHP_AUTH_USER'] != OPERATOR_NAME ||$_SERVER['PHP_AUTH_PW'] != OPERATOR_PASSWORD) {
			Header("WWW-Authenticate: Basic realm=\"Login\"");
			Header("HTTP/1.0 401 Unauthorized");

			echo <<<EOB
				<html><body>
				<h1>Rejected!</h1>
				<big>Wrong Username or Password!</big>
				</body></html>
EOB;
			exit;
}

///////////MEMCACHE FUNCTIONS /////////////////////////////////////////////////////////////////////

function sendUpyunCommands($command){
    global $BUCKET_NAMES;
	$result = array();

	foreach($BUCKET_NAMES as $bid => $bucket){
		$result[$bucket] = sendUpyunCommand($bid, $command);
	}
	return $result;
}

function sendUpyunCommand($command, $path = "/"){
	$upyun = new UpYun(BUCKET_NAME, OPERATOR_NAME, OPERATOR_PASSWORD);
	switch ($command) {
		case "usage": // bucket usage
			$method = "getFolderUsage";
			break;
		case "items": //bucket items
			$method = "getList";
			break;
	}
	$resp = array();
	try {
	    $resp["result"] = $upyun->$method($path);
	}
	catch(Exception $e) {
	    $resp["code"] = $e->getCode();
	    $resp["message"] = $e->getMessage();
	}
	//print_r($resp);
	/*
	return array(
		0 => array(
			'name' => "me.jpg",
            'type' => "file",
            'size' => 28236,
            'time' => 1397531334
		),
		1 => array(
			'name' => "demo",
            'type' => "folder",
            'size' => 0,
            'time' => 1400145889
		)
	);
	*/
	if (key_exists("result", $resp)){
		return $resp["result"];
	}else{
		return false;
	}
}

//////////////////////////////////////////////////////

//
// don't cache this page
//
header("Cache-Control: no-store, no-cache, must-revalidate");  // HTTP/1.1
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");                                    // HTTP/1.0
// create graphics
//
function graphics_avail() {
	return extension_loaded('gd');
}

function bsize($s) {
	foreach (array('','K','M','G') as $i => $k) {
		if ($s < 1024) break;
		$s/=1024;
	}
	return sprintf("%5.1f %sBytes",$s,$k);
}

function ext2img($ext){
	global $extensions;
	if (!array_key_exists($ext, $extensions)){
		$ext = "default";
	}
	return '<img height="16" src="data:image/gif;base64,' . $extensions[$ext] . '">';
}

// create menu entry
function menu_entry($ob,$title) {
	global $PHP_SELF;
	if ($ob==$_GET['op']){
	    return "<li><a class=\"child_active\" href=\"$PHP_SELF&op=$ob\">$title</a></li>";
	}
	return "<li><a class=\"active\" href=\"$PHP_SELF&op=$ob\">$title</a></li>";
}

function getHeader(){
    $header = <<<EOB
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head><title>Upyun Bucket Manage</title>
<style type="text/css"><!--
body { background:white; font-size:100.01%; margin:0; padding:0; }
body,p,td,th,input,submit { font-size:0.8em;font-family:arial,helvetica,sans-serif; }
* html body   {font-size:0.8em}
* html p      {font-size:0.8em}
* html td     {font-size:0.8em}
* html th     {font-size:0.8em}
* html input  {font-size:0.8em}
* html submit {font-size:0.8em}
td { vertical-align:top }
a { color:black; font-weight:none; text-decoration:none; }
a:hover { text-decoration:underline; }
div.content { padding:1em 1em 1em 1em; position:absolute; width:97%; z-index:100; }

h1.memcache { background:rgb(153,153,204); margin:0; padding:0.5em 1em 0.5em 1em; }
* html h1.memcache { margin-bottom:-7px; }
h1.memcache a:hover { text-decoration:none; color:rgb(90,90,90); }
h1.memcache span.logo {
	background:rgb(119,123,180);
	color:black;
	border-right: solid black 1px;
	border-bottom: solid black 1px;
	font-style:italic;
	font-size:1em;
	padding-left:1.2em;
	padding-right:1.2em;
	text-align:right;
	display:block;
	width:130px;
	}
h1.memcache span.logo span.name { color:white; font-size:0.7em; padding:0 0.8em 0 2em; }
h1.memcache span.nameinfo { color:white; display:inline; font-size:0.4em; margin-left: 3em; }
h1.memcache div.copy { color:black; font-size:0.4em; position:absolute; right:1em; }
hr.memcache {
	background:white;
	border-bottom:solid rgb(102,102,153) 1px;
	border-style:none;
	border-top:solid rgb(102,102,153) 10px;
	height:12px;
	margin:0;
	margin-top:1px;
	padding:0;
}

ol,menu { margin:1em 0 0 0; padding:0.2em; margin-left:1em;}
ol.menu li { display:inline; margin-right:0.7em; list-style:none; font-size:85%}
ol.menu a {
	background:rgb(153,153,204);
	border:solid rgb(102,102,153) 2px;
	color:white;
	font-weight:bold;
	margin-right:0em;
	padding:0.1em 0.5em 0.1em 0.5em;
	text-decoration:none;
	margin-left: 5px;
	}
ol.menu a.child_active {
	background:rgb(153,153,204);
	border:solid rgb(102,102,153) 2px;
	color:white;
	font-weight:bold;
	margin-right:0em;
	padding:0.1em 0.5em 0.1em 0.5em;
	text-decoration:none;
	border-left: solid black 5px;
	margin-left: 0px;
	}
ol.menu span.active {
	background:rgb(153,153,204);
	border:solid rgb(102,102,153) 2px;
	color:black;
	font-weight:bold;
	margin-right:0em;
	padding:0.1em 0.5em 0.1em 0.5em;
	text-decoration:none;
	border-left: solid black 5px;
	}
ol.menu span.inactive {
	background:rgb(193,193,244);
	border:solid rgb(182,182,233) 2px;
	color:white;
	font-weight:bold;
	margin-right:0em;
	padding:0.1em 0.5em 0.1em 0.5em;
	text-decoration:none;
	margin-left: 5px;
	}
ol.menu a:hover {
	background:rgb(193,193,244);
	text-decoration:none;
	}


div.info {
	background:rgb(204,204,204);
	border:solid rgb(204,204,204) 1px;
	margin-bottom:1em;
	}
div.info h2 {
	background:rgb(204,204,204);
	color:black;
	font-size:1em;
	margin:0;
	padding:0.1em 1em 0.1em 1em;
	}
div.info table {
	border:solid rgb(204,204,204) 1px;
	border-spacing:0;
	width:100%;
	}
div.info table th {
	background:rgb(204,204,204);
	color:white;
	margin:0;
	padding:0.1em 1em 0.1em 1em;
	}
div.info table th a.sortable { color:black; }
div.info table tr.tr-0 { background:rgb(238,238,238); }
div.info table tr.tr-1 { background:rgb(221,221,221); }
div.info table td { padding:0.3em 1em 0.3em 1em; }
div.info table td.td-0 { border-right:solid rgb(102,102,153) 1px; white-space:nowrap; }
div.info table td.td-n { border-right:solid rgb(102,102,153) 1px; }
div.info table td h3 {
	color:black;
	font-size:1.1em;
	margin-left:-0.3em;
	}
.td-0 a , .td-n a, .tr-0 a , tr-1 a {
    text-decoration:underline;
}
div.graph { margin-bottom:1em }
div.graph h2 { background:rgb(204,204,204);; color:black; font-size:1em; margin:0; padding:0.1em 1em 0.1em 1em; }
div.graph table { border:solid rgb(204,204,204) 1px; color:black; font-weight:normal; width:100%; }
div.graph table td.td-0 { background:rgb(238,238,238); }
div.graph table td.td-1 { background:rgb(221,221,221); }
div.graph table td { padding:0.2em 1em 0.4em 1em; }

div.div1,div.div2 { margin-bottom:1em; width:35em; }
div.div3 { position:absolute; left:40em; top:1em; width:580px; }
//div.div3 { position:absolute; left:37em; top:1em; right:1em; }

div.sorting { margin:1.5em 0em 1.5em 2em }
.center { text-align:center }
.aright { position:absolute;right:1em }
.right { text-align:right }
.ok { color:rgb(0,200,0); font-weight:bold}
.failed { color:rgb(200,0,0); font-weight:bold}

span.box {
	border: black solid 1px;
	border-right:solid black 2px;
	border-bottom:solid black 2px;
	padding:0 0.5em 0 0.5em;
	margin-right:1em;
}
span.green { background:#60F060; padding:0 0.5em 0 0.5em}
span.red { background:#D06030; padding:0 0.5em 0 0.5em }

div.authneeded {
	background:rgb(238,238,238);
	border:solid rgb(204,204,204) 1px;
	color:rgb(200,0,0);
	font-size:1.2em;
	font-weight:bold;
	padding:2em;
	text-align:center;
	}

input {
	background:rgb(153,153,204);
	border:solid rgb(102,102,153) 2px;
	color:white;
	font-weight:bold;
	margin-right:1em;
	padding:0.1em 0.5em 0.1em 0.5em;
	}
//-->
</style>
</head>
<body>
<div class="head">
	<h1 class="memcache">
		<span class="logo"><a href="https://www.upyun.com/cp/#/login/">Upyun</a></span>
		<span class="nameinfo">upyun.php by <a href="http://blog.iscsky.net">Garfielt</a></span>
	</h1>
	<hr class="memcache">
</div>
<div class=content>
EOB;

    return $header;
}
function getFooter(){
    global $VERSION;
    $footer = '</div><!-- Based on apc.php '.$VERSION.'--></body>
</html>
';

    return $footer;

}
function getMenu(){
    global $PHP_SELF;
echo "<ol class=menu>";
if ($_GET['op']!=4){
echo <<<EOB
    <li><a href="$PHP_SELF&op={$_GET['op']}&cp={$_GET['cp']}">Refresh Data</a></li>
EOB;
}
else {
echo <<<EOB
    <li><a href="$PHP_SELF&op=2}">Back</a></li>
EOB;
}
echo
	menu_entry(1,'View Host Stats'),
	menu_entry(2,'Variables'),
	menu_entry(3,'Local');

echo <<<EOB
	</ol>
	<br/>
EOB;
}

// TODO, AUTH

$_GET['op'] = !isset($_GET['op'])? '1':$_GET['op'];
$_GET['cp'] = !isset($_GET['cp'])? '/':$_GET['cp'];
$PHP_SELF= isset($_SERVER['PHP_SELF']) ? htmlentities(strip_tags($_SERVER['PHP_SELF'],'')) : '';

$PHP_SELF=$PHP_SELF.'?';
$time = time();
// sanitize _GET

foreach($_GET as $key=>$g){
    $_GET[$key]=htmlentities($g);
}

// display images
if (isset($_GET['IMG'])){
    $memcacheStats = getMemcacheStats();
    $memcacheStatsSingle = getMemcacheStats(false);

    if (!graphics_avail()) {
		exit(0);
	}

	function fill_box($im, $x, $y, $w, $h, $color1, $color2,$text='',$placeindex='') {
		global $col_black;
		$x1=$x+$w-1;
		$y1=$y+$h-1;

		imagerectangle($im, $x, $y1, $x1+1, $y+1, $col_black);
		if($y1>$y) imagefilledrectangle($im, $x, $y, $x1, $y1, $color2);
		else imagefilledrectangle($im, $x, $y1, $x1, $y, $color2);
		imagerectangle($im, $x, $y1, $x1, $y, $color1);
		if ($text) {
			if ($placeindex>0) {

				if ($placeindex<16)
				{
					$px=5;
					$py=$placeindex*12+6;
					imagefilledrectangle($im, $px+90, $py+3, $px+90-4, $py-3, $color2);
					imageline($im,$x,$y+$h/2,$px+90,$py,$color2);
					imagestring($im,2,$px,$py-6,$text,$color1);

				} else {
					if ($placeindex<31) {
						$px=$x+40*2;
						$py=($placeindex-15)*12+6;
					} else {
						$px=$x+40*2+100*intval(($placeindex-15)/15);
						$py=($placeindex%15)*12+6;
					}
					imagefilledrectangle($im, $px, $py+3, $px-4, $py-3, $color2);
					imageline($im,$x+$w,$y+$h/2,$px,$py,$color2);
					imagestring($im,2,$px+2,$py-6,$text,$color1);
				}
			} else {
				imagestring($im,4,$x+5,$y1-16,$text,$color1);
			}
		}
	}


    function fill_arc($im, $centerX, $centerY, $diameter, $start, $end, $color1,$color2,$text='',$placeindex=0) {
		$r=$diameter/2;
		$w=deg2rad((360+$start+($end-$start)/2)%360);


		if (function_exists("imagefilledarc")) {
			// exists only if GD 2.0.1 is avaliable
			imagefilledarc($im, $centerX+1, $centerY+1, $diameter, $diameter, $start, $end, $color1, IMG_ARC_PIE);
			imagefilledarc($im, $centerX, $centerY, $diameter, $diameter, $start, $end, $color2, IMG_ARC_PIE);
			imagefilledarc($im, $centerX, $centerY, $diameter, $diameter, $start, $end, $color1, IMG_ARC_NOFILL|IMG_ARC_EDGED);
		} else {
			imagearc($im, $centerX, $centerY, $diameter, $diameter, $start, $end, $color2);
			imageline($im, $centerX, $centerY, $centerX + cos(deg2rad($start)) * $r, $centerY + sin(deg2rad($start)) * $r, $color2);
			imageline($im, $centerX, $centerY, $centerX + cos(deg2rad($start+1)) * $r, $centerY + sin(deg2rad($start)) * $r, $color2);
			imageline($im, $centerX, $centerY, $centerX + cos(deg2rad($end-1))   * $r, $centerY + sin(deg2rad($end))   * $r, $color2);
			imageline($im, $centerX, $centerY, $centerX + cos(deg2rad($end))   * $r, $centerY + sin(deg2rad($end))   * $r, $color2);
			imagefill($im,$centerX + $r*cos($w)/2, $centerY + $r*sin($w)/2, $color2);
		}
		if ($text) {
			if ($placeindex>0) {
				imageline($im,$centerX + $r*cos($w)/2, $centerY + $r*sin($w)/2,$diameter, $placeindex*12,$color1);
				imagestring($im,4,$diameter, $placeindex*12,$text,$color1);

			} else {
				imagestring($im,4,$centerX + $r*cos($w)/2, $centerY + $r*sin($w)/2,$text,$color1);
			}
		}
	}
	$size = GRAPH_SIZE; // image size
	$image = imagecreate($size+50, $size+10);

	$col_white = imagecolorallocate($image, 0xFF, 0xFF, 0xFF);
	$col_red   = imagecolorallocate($image, 0xD0, 0x60,  0x30);
	$col_green = imagecolorallocate($image, 0x60, 0xF0, 0x60);
	$col_black = imagecolorallocate($image,   0,   0,   0);

	imagecolortransparent($image,$col_white);

    switch ($_GET['IMG']){
        case 1: // pie chart
            $tsize=$memcacheStats['limit_maxbytes'];
    		$avail=$tsize-$memcacheStats['bytes'];
    		$x=$y=$size/2;
    		$angle_from = 0;
    		$fuzz = 0.000001;

            foreach($memcacheStatsSingle as $serv=>$mcs) {
    			$free = $mcs['STAT']['limit_maxbytes']-$mcs['STAT']['bytes'];
    			$used = $mcs['STAT']['bytes'];


                if ($free>0){
    			// draw free
    			    $angle_to = ($free*360)/$tsize;
                    $perc =sprintf("%.2f%%", ($free *100) / $tsize) ;

        			fill_arc($image,$x,$y,$size,$angle_from,$angle_from + $angle_to ,$col_black,$col_green,$perc);
        			$angle_from = $angle_from + $angle_to ;
                }
    			if ($used>0){
    			// draw used
        			$angle_to = ($used*360)/$tsize;
        			$perc =sprintf("%.2f%%", ($used *100) / $tsize) ;
        			fill_arc($image,$x,$y,$size,$angle_from,$angle_from + $angle_to ,$col_black,$col_red, '('.$perc.')' );
                    $angle_from = $angle_from+ $angle_to ;
    			}
    			}

        break;

        case 2: // hit miss

            $hits = ($memcacheStats['get_hits']==0) ? 1:$memcacheStats['get_hits'];
            $misses = ($memcacheStats['get_misses']==0) ? 1:$memcacheStats['get_misses'];
            $total = $hits + $misses ;

	       	fill_box($image, 30,$size,50,-$hits*($size-21)/$total,$col_black,$col_green,sprintf("%.1f%%",$hits*100/$total));
		    fill_box($image,130,$size,50,-max(4,($total-$hits)*($size-21)/$total),$col_black,$col_red,sprintf("%.1f%%",$misses*100/$total));
		break;
		
    }
    header("Content-type: image/png");
	imagepng($image);
	exit;
}

echo getHeader();
echo getMenu();

switch ($_GET['op']) {

    case 1: // host stats
    	$phpversion = phpversion();
        $bucketUsage = sendUpyunCommand("usage");
        $items = sendUpyunCommand("items");
        $total_items = count($items);

	    echo <<< EOB
		<div class="info div1"><h2>General Information</h2>
		<table cellspacing=0><tbody>
		<tr class=tr-1><td class=td-0>PHP Version</td><td>$phpversion</td></tr>
EOB;
		echo "<tr class=tr-0><td class=td-0>Bucket Space</td><td>";
		echo BUCKET_NAME;
		echo "</td></tr>\n";
		echo "<tr class=tr-1><td class=td-0>Total Bucket Storage</td><td>".bsize($bucketUsage)."</td></tr>\n";

	echo <<<EOB
		</tbody></table>
		</div>
		<div class="graph div3"><h2>Bucket Status Diagrams</h2>
		<table cellspacing=0><tbody>
EOB;

	$size='width='.(GRAPH_SIZE+50).' height='.(GRAPH_SIZE+10);
	echo <<<EOB
		<tr>
		<td class=td-0>Cache Usage</td>
		<td class=td-1>Hits &amp; Misses</td>
		</tr>
EOB;
		echo <<< EOB
	</tr>
	</tbody></table>
<br/>
	<div class="info"><h2>Bucket Information</h2>
		<table cellspacing=0><tbody>
EOB;
		echo "<tr class=tr-0><td class=td-0>Bucket Items(total)</td><td> " . bsize($bucketUsage) . " </td></tr>";
		echo <<< EOB
		<tr class=tr-1><td class=td-0>Bucket Items(total)</td><td> $total_items </td></tr>
		<tr class=tr-0><td class=td-0>Folders</td><td> </td></tr>
		<tr class=tr-1><td class=td-0>Files</td><td> </td></tr>
		</tbody></table>
		</div>

EOB;

    break;

    case 2: // variables

		$m=0;
		$totalSize = 0;
		$curpath = $_GET["cp"];
		$items = sendUpyunCommand("items", $path = $curpath);
		$totals = count($items);
		
		echo '<div class="info"><table cellspacing=0><tbody>';
		echo '<tr><th colspan="6"> Bucket: ' . BUCKET_NAME . ' CurrentPath: ' . $curpath . '<br><br></th></tr>';
    	echo '<tr><th>ID</th><th>Item</th><th>Type</th><th>Size</th><th>CreatTime</th><th>Operation</th></tr>';

		foreach($items as $k => $item) {
		    $baseUrl =  ($item["type"] == "file") ? 'http://'.BUCKET_NAME.".b0.upaiyun.com".$curpath.$item["name"] : $PHP_SELF.'&op=2&cp='.$curpath.$item["name"].'/';
		    $operUrl = $PHP_SELF.'&op=5&cp='.$curpath . $item["name"] . (($item["type"] == "file") ? "" : "/");
		    $extimg = ($item["type"] == "file") ? ext2img(pathinfo($item["name"], PATHINFO_EXTENSION)) : ext2img("folder");
			echo
				"<tr class=tr-$m>",
				"<td class=td-0><center>",($m+1),"</center></td>",
				"<td class=td-0><center>", '<a href="', $baseUrl, ($item["type"] == "file") ? '" target="_blank">' : '">', $item["name"], '</a></center></td>',
				"<td class=td-0><center><b>", $extimg, " </b></center></td>",
				"<td class=td-0><center>", bsize($item["size"]), "</center></td>",
				"<td class=td-0><center>", date(DATE_FORMAT, $item["time"]), "</center></td>",
				"<td class=td-last><center><b>", '<a href="', $operUrl, '&o=rename">Rename</a>',' | <a href="', $operUrl, '&o=move">Move</a>',' | <a href="', $operUrl, '&o=delete">Delete</a>',"</center></td></tr>";
			$m=1-$m;
			$totalSize += $item["size"];
		}
		echo '<tr><th colspan="6"> TotalSize: '.bsize($totalSize).'</th></tr>';
		echo <<<EOB
			</tbody></table>
			</div>
EOB;
		break;

    break;

    case 4: //item dump
        if (!isset($_GET['key']) || !isset($_GET['server'])){
            echo "No key set!";
            break;
        }
        // I'm not doing anything to check the validity of the key string.
        // probably an exploit can be written to delete all the files in key=base64_encode("\n\r delete all").
        // somebody has to do a fix to this.
        $theKey = htmlentities(base64_decode($_GET['key']));

        $theserver = $MEMCACHE_SERVERS[(int)$_GET['server']];
        list($h,$p) = get_host_port_from_server($theserver);
        $r = sendMemcacheCommand($h,$p,'get '.$theKey);
        echo <<<EOB
        <div class="info"><table cellspacing=0><tbody>
			<tr><th>Server<th>Key</th><th>Value</th><th>Delete</th></tr>
EOB;
        if (!isset($r['VALUE'])) {
            echo "<tr><td class=td-0>",$theserver,"</td><td class=td-0>",$theKey,
                 "</td><td>[The requested item was not found or has expired]</td>",
                 "<td></td>","</tr>";
        }
        else {

            echo "<tr><td class=td-0>",$theserver,"</td><td class=td-0>",$theKey,
                 " <br/>flag:",$r['VALUE'][$theKey]['stat']['flag'],
                 " <br/>Size:",bsize($r['VALUE'][$theKey]['stat']['size']),
                 "</td><td>",chunk_split($r['VALUE'][$theKey]['value'],40),"</td>",
                 '<td><a href="',$PHP_SELF,'&op=5&server=',(int)$_GET['server'],'&key=',base64_encode($theKey),"\">Delete</a></td>","</tr>";
        }
        echo <<<EOB
			</tbody></table>
			</div><hr/>
EOB;
    break;
    case 5: // item delete
    	if (!isset($_GET['key']) || !isset($_GET['server'])){
			echo "No key set!";
			break;
        }
        $theKey = htmlentities(base64_decode($_GET['key']));
		$theserver = $MEMCACHE_SERVERS[(int)$_GET['server']];
		list($h,$p) = get_host_port_from_server($theserver);
        $r = sendMemcacheCommand($h,$p,'delete '.$theKey);
        echo 'Deleting '.$theKey.':'.$r;
	break;
    
   case 6: // flush server
        $theserver = $MEMCACHE_SERVERS[(int)$_GET['server']];
        $r = flushServer($theserver);
        echo 'Flush  '.$theserver.":".$r;
   break;
}
echo getFooter();

?>
